package sctu.edu.java.year2016.team02.project.service.UI;


import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by Eoly on 2016/6/18.
 */
public class ipSet {
    //判断ip格式
    public static boolean ipCheck(String text) {
        if (text != null && !text.isEmpty()) {
            // 定义正则表达式
            String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
            // 判断ip地址是否与正则表达式匹配
            return text.matches(regex);
        }
        return false;
    }
    //弹出一个对话框，可以对服务器的ip地址进行设置
    public static void setIp(){
        String ip=null;
        try {
            ip= InetAddress.getLocalHost().toString();
        } catch (UnknownHostException e) {
            System.out.println("获取ip失败");
        }
        JDialog setS = new JDialog(new JFrame(),"设置服务器接口",true);
        JLabel ipLabel = new JLabel("ip地址+接口:");
        JLabel iptip = new JLabel("本地ip:"+ip);
        JTextField ipAddress = new JTextField(StartAndClose.ipAddress);
        JTextField port = new JTextField();
        JButton connect =  new JButton("设置完毕");
        port.setDocument(new NumberLenghtLimitedDmt(5));
        port.setText(String.valueOf(StartAndClose.port));
        ipLabel.setBounds(20, 40, 90, 25);
        iptip.setBounds(20, 10, 330, 25);
        ipAddress.setBounds(100, 40, 100, 25);
        port.setBounds(205, 40, 50, 25);
        connect.setBounds(140, 80, 120, 25);
        connect.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!ipCheck(ipAddress.getText()) || ipAddress.getText().isEmpty()) {
                    JOptionPane.showMessageDialog(new JFrame(), "ip地址不正确或ip地址为空", "提示", JOptionPane.PLAIN_MESSAGE);
                } else if (port.getText().isEmpty()) {
                    JOptionPane.showMessageDialog(new JFrame(), "接口不能为空", "提示", JOptionPane.PLAIN_MESSAGE);
                } else {
                    StartAndClose.ipAddress = ipAddress.getText();
                    StartAndClose.port = Integer.valueOf(port.getText());
                    setS.dispose();
                }
            }
        });
        setS.setBounds(MainUI.screenWidth / 4, MainUI.ScreenHeight / 4, 350, 150);
        setS.setSize(350, 150);
        setS.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setS.setLayout(null);
        setS.add(ipAddress);
        setS.add(ipLabel);
        setS.add(iptip);
        setS.add(port);
        setS.add(connect);
        setS.setResizable(false);
        setS.setVisible(true);
    }
}
